const express = require('express')
const router = express.Router()
const db = require('../../connection/Connection')
const jwt = require('jsonwebtoken')
const SECRET = 'asdfta219*&%^jWJSHFJ'


router.post('/addDepartment', async (req, res) => {
    //token
    const result = jwt.verify(req.body.token, SECRET)
    let sql = 'select departmentId from user_role where username = ?'
    db.base(sql, result.username, response => {
        //验证成功
        if ( response.length > 0 && response[0].departmentId === 999) {
            console.log(req.body)
            //先查看该部门是否已经存在
            let sql = 'select * from departmentInfo_nostation where department_name = ? and region = ?'
            let data = [req.body.add_form.department_name, req.body.add_form.region]
            console.log(data)
            db.base(sql, data, response => {
                console.log(response)
                //该部门未存在
                if (response.length === 0) {
                    let sql = 'insert into department set ?'
                    db.base(sql, req.body.add_form, () => {
                        res.json({
                            'code': 200,
                            'result': 'true',
                            'type': 'addDepartment_success',
                            'content': '成功添加新部门'
                        })
                    })
                }
                else {
                    res.json({
                        'code': 403,
                        'result': 'false',
                        'type': 'addDepartment_exist',
                        'content': '部门已经存在'
                    })
                }
            })


        }
        else {
            res.json({
                'code': 403,
                'result': 'false',
                'type': 'non_access',
                'content': '无权限'
            })


        }
    })
})

module.exports = router
